home *** CD-ROM | disk | FTP | other *** search
- ' a class that contains an array of 100,000 random elements
-
- Class RandomArray
- Public ReadOnly arrRand(100000) As Double
-
- ' the constructor creates the random array
- Sub New()
- Dim i As Integer
- Dim rand As New Random()
- ' a time consuming operation
- For i = 0 To UBound(arrRand)
- arrRand(i) = rand.NextDouble
- Next
- End Sub
- End Class
-
- ' this is the version of RandomArray that is ready to be pooled
-
- Class RandomArrayPooled
- Inherits RandomArray
-
- ' A reference to the pool manager for this class
- Public OwnerPoolManager As PoolManager
-
- Protected Overrides Sub Finalize()
- If OwnerPoolManager Is Nothing Then
- ' This instance isn't owned by a pool manager
-
- ElseIf OwnerPoolManager.PooledObjects Is Nothing Then
- ' This instance has an owner pool manager, but it was already finalized
-
- Else
- ' when this object is finalized, put it back in the pooledobjects stack
- OwnerPoolManager.PooledObjects.Push(Me)
- ' re-register this object for the Finalize method
- GC.ReRegisterForFinalize(Me)
- End If
- End Sub
- End Class
-
- ' a class that pools one or more RandomArray objects
-
- Class PoolManager
- Implements IDisposable
-
- ' this stack contains all the objects in the pool
- Public PooledObjects As New Stack()
-
- ' return a new instance of the RandomArray class
- Function NewRandomArray() As RandomArrayPooled
- If PooledObjects.Count > 1 Then
- ' if there is an object in the pool, use it
- Return DirectCast(PooledObjects.Pop, RandomArrayPooled)
- Else
- ' otherwise create a new object
- NewRandomArray = New RandomArrayPooled()
- NewRandomArray.OwnerPoolManager = Me
- End If
- End Function
-
- Sub Dispose() Implements IDisposable.Dispose
- ' first, suppress Finalize for all pooled objects
- Dim ra As RandomArray
-
- For Each ra In PooledObjects
- DirectCast(ra, RandomArrayPooled).OwnerPoolManager = Nothing
- GC.SuppressFinalize(ra)
- Next
-
- ' inform other objects not to hook this parent pool manager again
- PooledObjects = Nothing
- End Sub
-
- End Class
-